/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.backendbean;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.retabel.jsf.FailureObjectUriBuilder;
import org.retabel.jsf.PagedListDataModel;
import org.retabel.ui.FailureObjectUI;
import org.retabel.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xsd.failureobjects.FailureObject;
import xsd.failureobjects.FailureObjects;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

@ManagedBean
@RequestScoped
@Named
public class FailureObjectListBean extends PagedListBean {

    // constants

    private static final Logger log = LoggerFactory.getLogger(FailureObjectListBean.class);

    // private fields

    private LogLines logLines = new LogLines(log);

    // private functions

    private FailureObjects getPage(int first, int maxRows) throws Exception {
        // we don't want any log lines, use null as log lines parameter therefore
        return new HttpGetClientRequestRunner<FailureObjects>(null) {
            @Override
            protected FailureObjects onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                return JaxbUtils.unmarshal(FailureObjectUriBuilder.getFailureObjectsXmlSchemaURI().toURL(),
                                           response.getEntity().getContent(), FailureObjects.class);
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "request failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(FailureObjectUriBuilder.getFailureObjectsURI(first, maxRows));
    }

    // protected methods

    @Override
    protected DataModel getDataModel() throws Exception {
        FailureObjects failureObjects = getPage(getUiData().getFirst(), getUiData().getRows());

        List<FailureObjectUI> failureObjectUIs = new ArrayList<>();
        int count = 0;

        if (failureObjects != null && failureObjects.getList() != null) {
            count = failureObjects.getCount();

            for (FailureObject failureObject : failureObjects.getList().getFailureObject()) {
                FailureObjectUI failureObjectUI = new FailureObjectUI();

                failureObjectUI.setId(failureObject.getId());
                failureObjectUI.setClassName(failureObject.getClassName());

                if (failureObject.getCreated() != null) {
                    failureObjectUI.setCreated(failureObject.getCreated().toGregorianCalendar().getTime());
                }
                if (failureObject.getLastRedo() != null) {
                    failureObjectUI.setLastRedo(failureObject.getLastRedo().toGregorianCalendar().getTime());
                }

                failureObjectUIs.add(failureObjectUI);
            }
        }

        return new PagedListDataModel(failureObjectUIs, count, getUiData().getRows());
    }

    // public functions

    public void redo() throws Exception {
        FailureObjectUI failureObjectUI = (FailureObjectUI) getUiData().getRowData();

        new HttpPutClientRequestRunner<Boolean>(logLines) {

            @Override
            protected HttpEntity getHttpEntity() throws Exception {
                return null;
            }

            @Override
            protected Boolean onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                                                                                    "failure object reinitiated "
                                                                                    + "successfully",
                                                                                    response.getStatusLine().toString()));

                return Boolean.TRUE;
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "failure object could not been reinitiated",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(FailureObjectUriBuilder.getFailureObjectRedoURI(failureObjectUI.getId()));
    }

    @Override
    public void delete() throws Exception {
        FailureObjectUI failureObjectUI = (FailureObjectUI) getUiData().getRowData();

        new HttpDeleteClientRequestRunner<Boolean>(logLines) {
            @Override
            protected Boolean onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                                                                                    "failure object deleted "
                                                                                    + "successfully",
                                                                                    response.getStatusLine().toString()));

                return Boolean.TRUE;
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "failure object could not been deleted",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(FailureObjectUriBuilder.getFailureObjectDeleteURI(failureObjectUI.getId()));
    }

}